var http = require("http");
var formidable = require("formidable");
var fs = require("fs");

http
  .createServer(function (req, res) {
    console.log("req.url = " + req.url);
    if (req.url == "/file-upload") {
      var form = new formidable.IncomingForm();
      form.parse(req, function (err, fields, files) {
        // console.log(files)
        var oldPath = files.file.filepath;
        var newPath = __dirname + "/img/" + files.file.originalFilename;
        console.log("oldPath = " + oldPath);
        console.log("newPath = " + newPath);
        var readStream = fs.createReadStream(oldPath);
        var writeStream = fs.createWriteStream(newPath);
        readStream.pipe(writeStream);
        readStream.on("end", function () {
          fs.unlinkSync(oldPath);
          res.write("File uploaded successfully");
          res.end();
        });
      });
    } else {
      res.write("url error!");
      res.end();
    }
  })
  .listen(3000);
